package com.atguigu.daijia.driver.service.impl;

import cn.hutool.json.JSONUtil;
import com.atguigu.daijia.driver.config.TencentCloudProperties;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    @Autowired
    private TencentCloudProperties tencentCloudProperties;


    /**
     * 该函数功能是创建并返回一个COSClient对象，用于访问腾讯云的对象存储服务（COS）。函数执行以下步骤：
     * 从tencentCloudProperties属性中获取用户密钥信息：SecretId和SecretKey。
     * 使用获取的密钥信息初始化BasicCOSCredentials对象cred。
     * 从tencentCloudProperties中获取地域信息，并初始化Region对象。
     * 创建ClientConfig对象并设置地域信息，同时设置使用https协议。
     * 最后，利用上述配置信息生成并返回一个COSClient对象，用于后续的腾讯云对象存储操作。
     *
     * @return
     */
    private COSClient getCOSClient() {
        // 初始化用户信息
        String secretId = tencentCloudProperties.getSecretId();
        String secretKey = tencentCloudProperties.getSecretKey();
        BasicCOSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 设置bucket 的地域，cos地域
        Region region = new Region(tencentCloudProperties.getRegion());
        // 设置使用https协议
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 生成cos 客户端
        return new COSClient(cred, clientConfig);
    }

    @Override
    @SneakyThrows
    public CosUploadVo upload(MultipartFile file, String path) {
        COSClient cosClient = this.getCOSClient();
        // 元数据信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.getSize()); // 设置文件大小
        meta.setContentEncoding("UTF-8"); // 设置编码格式
        meta.setContentType(file.getContentType()); //设置文件类型

        //向存储桶中保存文件
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); // 文件后缀名

        String uploadPath = "/driver/" + path + "/" + UUID.randomUUID().toString().replaceAll("-", "") + fileType; // 文件上传路径

        PutObjectRequest putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(), uploadPath, file.getInputStream(), meta);

        putObjectRequest.setStorageClass(StorageClass.Standard);
        // 上传文件
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        log.info(JSONUtil.toJsonStr(putObjectResult));
        cosClient.shutdown();

        // 封装返回对象
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(uploadPath);
        String imageUrl = this.getImageUrl(uploadPath);
        cosUploadVo.setShowUrl(imageUrl);
        return cosUploadVo;
    }

    @Override
    public String getImageUrl(String path) {

        // 判断路径
        if (!StringUtils.hasText(path)) return "";

        // 获取COSClient对象
        COSClient cosClient = this.getCOSClient();

        GeneratePresignedUrlRequest request =
                new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(), path, HttpMethodName.GET);

        // 设置临时URL有效为15分钟
        Date date = new DateTime().plusMillis(15).toDate();
        request.setExpiration(date);

        // 调用方法获取
        URL url = cosClient.generatePresignedUrl(request);
        cosClient.shutdown();
        return url.toString();
    }

}
